package com.ruoyi.project.mobile.order;

import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.uniquekey.IdGererateFactory;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.AppBeanInjector;
import com.ruoyi.project.system.address.domain.MemberAddress;
import com.ruoyi.project.system.address.service.IMemberAddressService;
import com.ruoyi.project.system.goods.cart.service.IShoppingCartService;
import com.ruoyi.project.system.goods.fee.domain.GoodsPostFee;
import com.ruoyi.project.system.goods.fee.service.IGoodsPostFeeService;
import com.ruoyi.project.system.goods.goods.domain.GoodsDto;
import com.ruoyi.project.system.goods.goods.domain.GoodsGoods;
import com.ruoyi.project.system.goods.goods.enums.GoodsTag;
import com.ruoyi.project.system.goods.goods.service.IGoodsGoodsService;
import com.ruoyi.project.system.goods.product.domain.GoodsProduct;
import com.ruoyi.project.system.goods.product.service.IGoodsProductService;
import com.ruoyi.project.system.member.domain.Member;
import com.ruoyi.project.system.member.enums.MemberIsVip;
import com.ruoyi.project.system.member.service.IMemberService;
import com.ruoyi.project.system.order.comment.dto.OrderCommentDto;
import com.ruoyi.project.system.order.comment.service.IOrderCommentService;
import com.ruoyi.project.system.order.commentimg.domain.CommentImg;
import com.ruoyi.project.system.order.commentimg.service.ICommentImgService;
import com.ruoyi.project.system.order.order.domain.OrderOrder;
import com.ruoyi.project.system.order.order.dto.OrderOrderDto;
import com.ruoyi.project.system.order.order.enums.OrderPayType;
import com.ruoyi.project.system.order.order.enums.OrderStatus;
import com.ruoyi.project.system.order.order.service.IOrderOrderService;
import com.ruoyi.project.system.order.ordergoods.domain.OrderGoods;
import com.ruoyi.project.system.order.ordergoods.dto.OrderGoodsDto;
import com.ruoyi.project.system.order.ordergoods.service.IOrderGoodsService;
import com.ruoyi.project.system.order.refuse.domain.OrderRefuse;
import com.ruoyi.project.system.order.refuse.service.IOrderRefuseService;
import com.ruoyi.project.system.paylog.domain.PayLog;
import com.ruoyi.project.system.paylog.service.IPayLogService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * 功能：
 *
 * @author：dell
 * @create：2020/6/22 18:54
 * @version：2020 Version：1.0
 * @company：老屋新房 Created with IntelliJ IDEA
 */
@RestController
@RequestMapping("/api/order")
public class ApiOrderController extends BaseController {

	@Autowired
	private IMemberAddressService memberAddressService;

	@Autowired
	private IGoodsGoodsService goodsGoodsService;

	@Autowired
	private IMemberService memberService;

	@Resource
	private IdGererateFactory idGererateFactory;

	@Autowired
	private IOrderOrderService orderOrderService;

	@Autowired
	private IOrderGoodsService orderGoodsService;

	@Autowired
	private IGoodsProductService goodsProductService;

	@Autowired
	private IOrderCommentService orderCommentService;

	@Autowired
	private ServerConfig serverConfig;

	@Autowired
	private ICommentImgService commentImgService;

	@Autowired
	private IShoppingCartService shoppingCartService;

	@Autowired
	private IOrderRefuseService orderRefuseService;
	@Autowired
	private IPayLogService payLogService;
	@Autowired
	private IGoodsPostFeeService goodsPostFeeService;

	@GetMapping("/ready")
	public R readyOrder(@RequestParam String uid,@RequestParam String[] productIds,@RequestParam Integer[] nums){
		if(productIds.length==0){
			return R.error("请至少一件商品");
		}
		HashMap<String, Object> map = new HashMap<>();
		//查询默认地址信息
		MemberAddress memberAddress = this.memberAddressService.findDefault(uid);
		map.put("address",memberAddress);
		//默认审核通过
		map.put("examine",0);
		//查询商品信息
		BigDecimal sumGoodsPrice = new BigDecimal(0);
		BigDecimal sumPostFee = new BigDecimal(0);
		int goodsCount = 0;
		ArrayList<GoodsDto> goodsDtos = new ArrayList<>();
		Member member = this.memberService.selectMemberById(uid);
		for(int i=0;i<productIds.length;i++){
			GoodsDto goodsDto = this.goodsGoodsService.findGoodsDtoByPId(productIds[i]);
			goodsDto.setTotal(nums[i]);
			goodsDto.setSpecId(productIds[i]);
			goodsDtos.add(goodsDto);
			if(member.getIsVip().equals(MemberIsVip.YES.getValue())){
				sumGoodsPrice=sumGoodsPrice.add(goodsDto.getPriceVip().multiply(new BigDecimal(nums[i])));
			}else{
				sumGoodsPrice=sumGoodsPrice.add(goodsDto.getPriceN().multiply(new BigDecimal(nums[i])));
			}
			// 获取该地区的运费
			List<GoodsPostFee> goodsPostFeeList = this.goodsPostFeeService.findListByGoodsId(goodsDto.getId());
			for(GoodsPostFee goodsPostFee :goodsPostFeeList){
				if(memberAddress.getArea().indexOf(goodsPostFee.getName())!=-1){
					goodsDto.setPostFee(goodsPostFee.getPostFee());
					break;
				}
			}
			sumPostFee=sumPostFee.add(goodsDto.getPostFee());
			goodsCount=goodsCount+nums[i];
			//判断商品是否是境外商品
			if(!goodsDto.getTag().equals(GoodsTag.QUALITY_GOODS.getValue())){
				//判断当前用户是否已认证
				if(!member.getIsExamine().equals(2)){
					map.put("examine",1);
				}
			}
		}
		map.put("sumPostFee",sumPostFee);
		map.put("sumGoodsPrice",sumGoodsPrice);
		map.put("sumPrice",sumGoodsPrice.add(sumPostFee));
		map.put("goods",goodsDtos);
		map.put("goodsCount",goodsCount);
		return RFactory.generateR(map);
	}

	/**
	 * 新增订单
	 * @param orderOrderDto
	 * @return
	 */
	@PostMapping
	@Transactional
	public R addOrder(@RequestBody OrderOrderDto orderOrderDto){
		Member member = this.memberService.selectMemberById(orderOrderDto.getUserId());
		//判断商品库存是否充足
		for(OrderGoods orderGoods:orderOrderDto.getGoodsList()){
			GoodsProduct goodsProduct = this.goodsProductService.selectGoodsProductById(orderGoods.getProductId());
			if(goodsProduct.getStock()<orderGoods.getTotal()){
				return R.error("库存不足,请重新下单");
			}
			//修改库存
			goodsProduct.setStock(goodsProduct.getStock()-orderGoods.getTotal().intValue());
			this.goodsProductService.updateGoodsProduct(goodsProduct);
			//修改商品库存
			GoodsGoods oldGoods = this.goodsGoodsService.selectGoodsGoodsById(goodsProduct.getGoodsId());


			//如果是秒杀商品 判断数量是否是1  是否以前已买过
			if(oldGoods.getHasSpike()==1){
				//判断是否在秒杀期间
				if (oldGoods.getSpikeStart().getTime() > DateUtils.getNowDate().getTime() || oldGoods.getSpikeEnd().getTime() < DateUtils.getNowDate().getTime()) {
					return R.error("秒杀商品:" + oldGoods.getName() + " 不在秒杀时间");
				}
				if(orderGoods.getTotal()!=1){
					return R.error("秒杀商品:" + oldGoods.getName() + "限购一件");
				}
				List<OrderGoods> oldOrderGoods = this.orderGoodsService.findListByUidAndPid(orderOrderDto.getUserId(),orderGoods.getProductId());
				if(oldOrderGoods.size()!=0){
					return R.error("秒杀商品:" + oldGoods.getName() + "您已够买过或者已经下过单");
				}
			}


			GoodsGoods updateGoods = new GoodsGoods();
			updateGoods.setId(oldGoods.getId());
			updateGoods.setStock(oldGoods.getStock()-orderGoods.getTotal());
			this.goodsGoodsService.updateGoodsGoods(updateGoods);
			//补充订单产品信息
			if(member.getIsVip().equals(MemberIsVip.YES.getValue())){
				orderGoods.setPriceN(goodsProduct.getPriceVip());
			}else{
				orderGoods.setPriceN(goodsProduct.getPriceN());
			}
			orderGoods.setPriceO(goodsProduct.getPriceO());
			orderGoods.setGoodsId(goodsProduct.getGoodsId());
		}

		//生成 上级订单ID
		String superOrderId = "";
		if(orderOrderDto.getGoodsList().size()>1){
			superOrderId = this.idGererateFactory.nextId().toString();
		}

		String orderId = "";

		for(OrderGoods orderGoods:orderOrderDto.getGoodsList()){
			OrderOrder order = new OrderOrder();
			order.setUserId(orderOrderDto.getUserId());
			order.setPostFee(orderGoods.getPostFee());
			order.setPricePay(orderGoods.getPriceN().multiply(new BigDecimal(orderGoods.getTotal())).add(order.getPostFee()));
			order.setPriceRealPay(order.getPricePay());
			order.setBuyerMsg(orderOrderDto.getBuyerMsg());
			order.setConsigneeName(orderOrderDto.getConsigneeName());
			order.setConsigneeTel(orderOrderDto.getConsigneeTel());
			order.setAddress(orderOrderDto.getAddress());
			order.setArea(orderOrderDto.getArea());
			if(orderOrderDto.getGoodsList().size()>1){
				order.setSuperOrderId(superOrderId);
			}

			order.setOrderNo(this.idGererateFactory.nextId().toString());
			order.setStatus(OrderStatus.TO_BE_PAID.getValue());
			order.setCreated(DateUtils.getNowDate());
			order.setDelFlag(0);
			order.setIsRefund(0);
			this.orderOrderService.insertOrderOrder(order);
			//添加订单下的产品信息
			orderGoods.setOrderId(order.getId());
			orderGoods.setHasComent(0);
			this.orderGoodsService.insertOrderGoods(orderGoods);

			if(orderOrderDto.getGoodsList().size()>1){
				order.setSuperOrderId(superOrderId);
				orderId = superOrderId;
			}else{
				orderId = order.getId();
			}
		}


		//补全订单信息
//		orderOrderDto.setOrderNo(this.idGererateFactory.nextId().toString());
//		orderOrderDto.setStatus(OrderStatus.TO_BE_PAID.getValue());
//		orderOrderDto.setCreated(DateUtils.getNowDate());
//		orderOrderDto.setDelFlag(0);
//		orderOrderDto.setIsRefund(0);
//		this.orderOrderService.insertOrderOrder(orderOrderDto);
//		//添加订单下的产品信息
//		for(OrderGoods orderGoods:orderOrderDto.getGoodsList()){
//			orderGoods.setOrderId(orderOrderDto.getId());
//			orderGoods.setHasComent(0);
//			this.orderGoodsService.insertOrderGoods(orderGoods);
//		}
		//删除购物车
		if(orderOrderDto.getCartIds()!=null){
			this.shoppingCartService.deleteByIds(orderOrderDto.getCartIds());
		}
		return RFactory.generateR(orderId);

	}

	/**
	 * 发起支付 获取支付必要参数
	 * @param uid
	 * @param id
	 * @param req
	 * @return
	 */
	@GetMapping("/wxpay")
	public R wxPay(@RequestParam String uid, @RequestParam String id, HttpServletRequest req){
		//查询订单是否存在
		OrderOrder orderOrder = this.orderOrderService.selectOrderOrderById(id);
		if(orderOrder!=null){
			if(!orderOrder.getUserId().equals(uid)){
				return R.error("订单不存在");
			}
		}else{
			List<OrderOrderDto> orderOrders = this.orderOrderService.findListBySuperOId(id);
			if(orderOrders==null||orderOrders.size()==0){
				return R.error("订单找不到");
			}
			BigDecimal price = new BigDecimal(0);
			for(OrderOrder order :orderOrders){
				price = price.add(order.getPriceRealPay());
			}
			orderOrder = new OrderOrder();
			orderOrder.setOrderNo(id);
			orderOrder.setPriceRealPay(price);
		}

		Member member = this.memberService.selectMemberById(uid);

		HashMap<String, Object> map = new HashMap<>();
		//时间戳
		map.put("timeStamp",(DateUtils.getNowDate().getTime()+"").substring(0,10));
		//package

		//调用统一下单接口拿到prepay_id
		SortedMap<String, Object> date = new TreeMap<String,Object>();

		//返回用前端的date2
		SortedMap<String, Object> date2 = new TreeMap<String,Object>();
		date2.put("appId",AppBeanInjector.weixinConfig.getAppId());
		date2.put("timeStamp",(DateUtils.getNowDate().getTime()+"").substring(0,10));
		date2.put("signType","MD5");

		date.put("appid",AppBeanInjector.weixinConfig.getAppId());
		date.put("attach","家禽生态订单");
		date.put("openid",member.getOpenid());
		date.put("body","家禽生态订单");
		date.put("mch_id",AppBeanInjector.weixinConfig.getMch_id());
		date.put("nonce_str",this.idGererateFactory.nextStringId());
		date.put("notify_url",AppBeanInjector.weixinConfig.getNotify_url());
		date.put("out_trade_no",orderOrder.getOrderNo()+"-"+this.idGererateFactory.nextStringId());
		date.put("spbill_create_ip",StringUtils.getRemoteAddr(req));
		float sessionmoney = Float.parseFloat(orderOrder.getPriceRealPay().toString());
		String finalmoney = String.format("%.2f", sessionmoney);
		finalmoney = finalmoney.replace(".", "");
		String newStr = finalmoney.replaceFirst("^0*", "");
		date.put("total_fee",newStr);
		date.put("trade_type","JSAPI");
		//统一下单 获取预支付ID
		String perpayId = WeixinUtils.getPerpayId(date,date2);

		date2.put("package",FBSStringUtil.format("prepay_id={0}",perpayId));

		map.put("package",FBSStringUtil.format("prepay_id={0}",perpayId));
		//paySign 签名
		map.put("paySign",WeixinUtils.createSign(WeixinUtils.CHARSET,date2));
		//随机字符串
		map.put("nonceStr",date2.get("nonceStr"));


		//生成支付记录
		PayLog payLog = new PayLog();
		payLog.setOutTradeNo((String) date.get("out_trade_no"));
		payLog.setStatus(0);
		payLog.setType(1);
		payLog.setCreated(DateUtils.getNowDate());
		payLog.setMemberId(uid);
		payLog.setResId(id);
		payLog.setPrice(orderOrder.getPriceRealPay());
		this.payLogService.insertPayLog(payLog);


		return RFactory.generateR(map);
	}


	/**
	 * 支付成功的回调参数
	 * @param req
	 * @param res
	 * @return
	 */
	@PostMapping("/result")
	public Object weixinResult(HttpServletRequest req, HttpServletResponse res){
		try {
			InputStream inStream = req.getInputStream();
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
				outSteam.write(buffer, 0, len);
			}

			System.out.println("~~~~~~~~~~~~~~~~付款成功~~~~~~~~~");
			outSteam.close();
			inStream.close();
			String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
			Map<Object, Object> mapFromXml = WeixinUtils.doXMLParse(result);
			SortedMap<String ,String > sortedMap = new TreeMap();
			if (mapFromXml.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {

				PayLog payLog = this.payLogService.selectPayLogByNo(mapFromXml.get("out_trade_no").toString());
				if(payLog.getStatus()==0){

					String orderNo = mapFromXml.get("out_trade_no").toString().split("-")[0];
					Date date = new Date();
					OrderOrderDto orderOrder = this.orderOrderService.findByOrderNo(orderNo);
					if (orderOrder!=null){
						if (orderOrder.getStatus()>0){
							return "fail";
						}
						//  验签成功后
						orderOrder.setStatus(1);
						orderOrder.setPayType(OrderPayType.WEIXIN.getValue());
						orderOrder.setUpdateTime(date);
						orderOrder.setOutTradeNo(mapFromXml.get("out_trade_no").toString());
						orderOrderService.updateOrderOrder(orderOrder);

						//产品销量新增

						//查询订单下的规格
						List<OrderGoodsDto> listByOrderId = this.orderGoodsService.findListByOrderId(orderOrder.getId());
						for(OrderGoodsDto orderGoodsDto:listByOrderId){
							GoodsGoods goodsGoods = this.goodsGoodsService.selectGoodsGoodsById(orderGoodsDto.getGoodsId());
							GoodsGoods update = new GoodsGoods();
							update.setId(goodsGoods.getId());
							update.setMonthlySales(goodsGoods.getMonthlySales()+orderGoodsDto.getTotal());
							this.goodsGoodsService.updateGoodsGoods(update);
						}
						//更新支付记录
						PayLog updatePayLog = new PayLog();
						updatePayLog.setId(payLog.getId());
						updatePayLog.setStatus(1);
						this.payLogService.updatePayLog(updatePayLog);
					}else{
						List<OrderOrderDto> listBySuperOId = this.orderOrderService.findListBySuperOId(orderNo);
						if(listBySuperOId==null||listBySuperOId.size()==0){
							sortedMap.put("return_code","FAIL");
							sortedMap.put("return_msg","签名失败");
							res.reset();
							res.getWriter().write(parseXML(sortedMap));
						}else{
							for(OrderOrderDto orderOrderDto: listBySuperOId){
								orderOrderDto.setStatus(1);
								orderOrderDto.setPayType(OrderPayType.WEIXIN.getValue());
								orderOrderDto.setUpdateTime(date);
								orderOrderDto.setOutTradeNo(mapFromXml.get("out_trade_no").toString());
								orderOrderService.updateOrderOrder(orderOrderDto);

								//产品销量新增

								//查询订单下的规格
								List<OrderGoodsDto> listByOrderId = this.orderGoodsService.findListByOrderId(orderOrderDto.getId());
								for(OrderGoodsDto orderGoodsDto:listByOrderId){
									GoodsGoods goodsGoods = this.goodsGoodsService.selectGoodsGoodsById(orderGoodsDto.getGoodsId());
									GoodsGoods update = new GoodsGoods();
									update.setId(goodsGoods.getId());
									update.setMonthlySales(goodsGoods.getMonthlySales()+orderGoodsDto.getTotal());
									this.goodsGoodsService.updateGoodsGoods(update);
								}
							}
							//更新支付记录
							PayLog updatePayLog = new PayLog();
							updatePayLog.setId(payLog.getId());
							updatePayLog.setStatus(1);
							this.payLogService.updatePayLog(updatePayLog);
						}
					}

				}


				sortedMap.put("return_code","SUCCESS");
				sortedMap.put("return_msg","OK");

				BufferedOutputStream out = new BufferedOutputStream(
						res.getOutputStream());
				out.write(parseXML(sortedMap).getBytes());
				out.flush();
				out.close();
			}else {
				sortedMap.put("return_code","FAIL");
				sortedMap.put("return_msg","签名失败");
				BufferedOutputStream out = new BufferedOutputStream(
						res.getOutputStream());
				out.write(parseXML(sortedMap).getBytes());
				out.flush();
				out.close();
			}
			return "success";
		} catch (Exception e) {
			return "failure";
		}
	}


	//输出XML
	public String parseXML(Map map) {
		StringBuffer sb = new StringBuffer();
		sb.append("<xml>\n");
		Set es = map.entrySet();
		Iterator it = es.iterator();
		while(it.hasNext()) {
			Map.Entry entry = (Map.Entry)it.next();
			String k = (String)entry.getKey();
			String v = (String)entry.getValue();
			if(null != v && !"".equals(v) && !"appkey".equals(k)) {

				sb.append("<" + k +"><![CDATA[" + v + "]]></" + k + ">\n");
			}
		}
		sb.append("</xml>");
		return sb.toString();
	}


	/**
	 * 订单收货
	 * @param map
	 * @return
	 */
	@PostMapping("/receipt")
	public R orderReceipt(@RequestBody Map map){
		String uid = (String) map.get("uid");
		String id = (String) map.get("id");

		//判断订单信息是否存在
		OrderOrder orderOrder = this.orderOrderService.selectOrderOrderById(id);
		//订单不存在 或者 订单并非当前用户 或者 订单 状态不是待收货
		if(orderOrder==null||!orderOrder.getUserId().equals(uid)||!orderOrder.getStatus().equals(OrderStatus.TO_BE_RECEIVED.getValue())){
			return R.error("订单未找到");
		}

		OrderOrder update = new OrderOrder();
		update.setStatus(OrderStatus.TO_BE_COMMENT.getValue());
		update.setId(id);
		update.setCloseTime(DateUtils.getNowDate());
		this.orderOrderService.updateOrderOrder(update);

		return R.ok();
	}

	/**
	 * 查询订单列表
	 * @param status
	 * @param uid
	 * @return
	 */
	@GetMapping
	public R orderList(@RequestParam(required = false) Integer[] status,@RequestParam String uid,@RequestParam(required = false) Integer refund){
		startPage();
		List<OrderOrderDto> orderOrderDtos = this.orderOrderService.findListByStatusAndUid(status,uid,refund);
		if(orderOrderDtos!=null){
			for(OrderOrderDto orderDto:orderOrderDtos){
				orderDto.setGoodsList(this.orderGoodsService.findListByOrderId(orderDto.getId()));
			}
		}
		return RFactory.generateR(orderOrderDtos);
	}


	/**
	 * 查询订单详情
	 * @param id
	 * @return
	 */
	@GetMapping("/info")
	public R orderInfo(@RequestParam String id){
		OrderOrderDto orderDto = this.orderOrderService.findByOrderId(id);
		if(orderDto!=null){
			orderDto.setGoodsList(this.orderGoodsService.findListByOrderId(id));
			return RFactory.generateR(orderDto);
		}else{
			List<OrderOrderDto> listBySuperOId = this.orderOrderService.findListBySuperOId(id);
			if(listBySuperOId==null||listBySuperOId.size()==0){
				return R.error("订单不存在");
			}
			OrderOrderDto order = listBySuperOId.get(0);
			ArrayList<OrderGoodsDto> orderGoods = new ArrayList<>();

			BigDecimal price = new BigDecimal(0);
			for(OrderOrderDto orderOrderDto:listBySuperOId){
				OrderGoodsDto orderGoodsDto = this.orderGoodsService.findListByOrderId(orderOrderDto.getId()).get(0);
				price = price.add(orderGoodsDto.getPriceN().multiply(new BigDecimal(orderGoodsDto.getTotal())).add(orderOrderDto.getPostFee())).setScale(2,BigDecimal.ROUND_HALF_UP);
				orderGoods.add(orderGoodsDto);
			}
			order.setGoodsList(orderGoods);
			order.setPriceRealPay(price.setScale(2,BigDecimal.ROUND_HALF_UP));
			order.setOrderNo(id);
			return RFactory.generateR(order);

		}

	}

	/**
	 * 取消订单
	 * @param map
	 * @return
	 */
	@PostMapping("/remove")
	public R removeOrder(@RequestBody Map map){
		String uid= (String) map.get("uid");
		String id = (String) map.get("id");
		//查询订单是否存在
		OrderOrder orderOrder = this.orderOrderService.selectOrderOrderById(id);
		if(orderOrder==null||!orderOrder.getUserId().equals(uid)){
			return R.error("订单不存在");
		}
		if(!orderOrder.getStatus().equals(OrderStatus.TO_BE_PAID.getValue())){
			return R.error("该状态下,不可取消");
		}
		OrderOrder order = new OrderOrder();
		order.setId(id);
		order.setStatus(OrderStatus.CANCEL.getValue());
		this.orderOrderService.updateOrderOrder(order);
		//释放订单下的产品库存
		List<OrderGoodsDto> listByOrderId = this.orderGoodsService.findListByOrderId(id);
		for(OrderGoodsDto orderGoodsDto:listByOrderId){
			GoodsProduct product = this.goodsProductService.selectGoodsProductById(orderGoodsDto.getProductId());
			//判断规格是否存在 以及 规格是否已删除
			if(product==null||product.getStatus().equals(1)){
				continue;
			}
			//修改规格库存
			GoodsProduct goodsProduct = new GoodsProduct();
			goodsProduct.setStock(product.getStock()+orderGoodsDto.getTotal().intValue());
			goodsProduct.setId(orderGoodsDto.getProductId());
			this.goodsProductService.updateGoodsProduct(goodsProduct);

			//修改产品库存
			GoodsGoods goods = this.goodsGoodsService.selectGoodsGoodsById(orderGoodsDto.getGoodsId());

			GoodsGoods goodsGoods = new GoodsGoods();
			goodsGoods.setId(orderGoodsDto.getGoodsId());
			goodsGoods.setStock(goods.getStock()+orderGoodsDto.getTotal());
			this.goodsGoodsService.updateGoodsGoods(goodsGoods);
		}


		return R.ok();
	}


	@PostMapping("/comment")
	@Transactional
	public R addOrderGoodsComment(@RequestBody OrderCommentDto orderCommentDto){
		//判断订单产品是否已评论
		OrderGoods orderGoods = new OrderGoods();
		orderGoods.setProductId(orderCommentDto.getProductId());
		orderGoods.setOrderId(orderCommentDto.getOrderId());
		List<OrderGoods> oldOrderGoods = this.orderGoodsService.selectOrderGoodsList(orderGoods);
		if(oldOrderGoods==null||oldOrderGoods.size()==0||oldOrderGoods.get(0).getHasComent().equals(1)){
			return R.error("不可以进行评论");
		}
		orderCommentDto.setCreated(DateUtils.getNowDate());
		orderCommentDto.setStatus(0);
		this.orderCommentService.insertOrderComment(orderCommentDto);

		//上传评论的图片
		if(orderCommentDto.getMultipartFiles()!=null&&orderCommentDto.getMultipartFiles().size()!=0){
			for(CommentImg commentImg:orderCommentDto.getMultipartFiles()){
					commentImg.setCommentId(orderCommentDto.getId());
					this.commentImgService.insertCommentImg(commentImg);
			}
		}


		//更新订单下的产品状态
		OrderGoods update = new OrderGoods();
		update.setId(oldOrderGoods.get(0).getId());
		update.setHasComent(1);
		this.orderGoodsService.updateOrderGoods(update);
		//判断订单下的产品是否已经全部评论
		OrderGoods oo = new OrderGoods();
		oo.setHasComent(0);
		oo.setOrderId(orderCommentDto.getOrderId());
		List<OrderGoods> og = this.orderGoodsService.selectOrderGoodsList(oo);
		if(og==null||og.size()==0){
			OrderOrder orderOrder = new OrderOrder();
			orderOrder.setId(orderCommentDto.getOrderId());
			orderOrder.setStatus(OrderStatus.COMPLETE.getValue());
			this.orderOrderService.updateOrderOrder(orderOrder);
		}

		return R.ok();
	}

	/**
	 * 新增售后
	 * @param orderRefuse
	 * @return
	 */
	@PostMapping("/refund")
	@Transactional
	public R orderRefund(@RequestBody OrderRefuse orderRefuse){
		OrderOrder oldOrder = this.orderOrderService.selectOrderOrderById(orderRefuse.getOrderId());
		if(oldOrder==null){
			return R.error("订单不存在");
		}
		//查询订单下是否已有售后单 防止重复提交
		OrderRefuse byNo = this.orderRefuseService.findByOrderId(oldOrder.getId());
		if(byNo!=null){
			return R.error("请勿重复提交");
		}

		orderRefuse.setPrice(oldOrder.getPriceRealPay());
		orderRefuse.setCreated(DateUtils.getNowDate());
//		orderRefuse.setRefundNo(this.idGererateFactory.nextStringId());
		orderRefuse.setStatus(0);
		this.orderRefuseService.insertOrderRefuse(orderRefuse);
		//修改订单为售后单
		OrderOrder orderOrder = new OrderOrder();
		orderOrder.setId(orderRefuse.getOrderId());
		orderOrder.setIsRefund(1);
		orderOrder.setStatus(5);
		this.orderOrderService.updateOrderOrder(orderOrder);
		return R.ok();
	}

	/**
	 * 查询快递信息
	 * @param uid
	 * @param id
	 * @return
	 */
	@GetMapping("/express")
	public R orderExpress(@RequestParam String uid,@RequestParam String id){
		//查询订单是否存在
		OrderOrderDto byOrderId = this.orderOrderService.findByOrderId(id);
		if(byOrderId==null||!byOrderId.getUserId().equals(uid)){
			return R.error("订单不存在");
		}
		byOrderId.setGoodsList(this.orderGoodsService.findListByOrderId(id));
		try {
//			JSONObject yd = AppBeanInjector.expressUtil.getOrderTracesByJson(byOrderId.getShippingCompanyCode(), byOrderId.getShippingCode());
			JSONObject expressJsonData = AppBeanInjector.kd100Util.getExpressJsonData(byOrderId.getShippingCompanyCode(), byOrderId.getShippingCode());
			HashMap<String, Object> map = new HashMap<>();
			map.put("order",byOrderId);
			map.put("express",expressJsonData.toString());
			return RFactory.generateR(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.error();
	}

}
